package control;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.service.ReserVationService;
import model.vo.movie.MovieVO;
import model.vo.mycinema.MemberVO;
import model.vo.reservation.PaymentConstants;
import model.vo.reservation.PaymentMethodInfoVO;
import model.vo.reservation.ReservationVO;
import model.vo.reservation.TimeTableVO;
import model.vo.theater.LocalInfoVO;
import model.vo.theater.PlayRoomVO;
import model.vo.theater.TheaterVO;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class ReservationController extends MultiActionController {
	private ReserVationService reserVationService;
	public ReservationController(ReserVationService reserVationService){
		this.reserVationService= reserVationService;
	}
	/**
	 * 예매 - 예매하기 (초기화면) 
	 * @throws SQLException 
	 */
	public ModelAndView reservation(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("reservation join..");
		HashMap map = null;
		if(request.getSession().getAttribute("vo")!=null){
			MemberVO vo = (MemberVO) request.getSession().getAttribute("vo");

			// 현재 상영중인 영화 목록 리스트
			ArrayList<HashMap> movie_list=null;
			try {
				movie_list = reserVationService.getScreeningMovieList();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(movie_list.toString());
			map = new HashMap();
			map.put("screening", movie_list);

			String voAge = vo.getSsn().substring(0, 2);
			int voBorn = Integer.parseInt(voAge);
			if(voBorn<20){
				voBorn = Integer.parseInt("20" + voAge);
			}else{
				voBorn = Integer.parseInt("19" + voAge);
			}	
			Calendar cal= Calendar.getInstance();
			int year= cal.get(Calendar.YEAR);
			System.out.println(year-voBorn+"살 ");
			int age= year-voBorn;
		/*	if(age<18){
				if(age<12){ 	
					map.put("voGrade", "12");
				}else if(age<15){
					map.put("voGrade", "15");
				}else if(age<18){
					map.put("voGrade", "18");
				}
			}else{
				map.put("voGrade", "19");
			}*/
			map.put("voAge", age);
			
		}		
		return new ModelAndView("reservation.reservation","list",map);
	}
	public ModelAndView getLocalListAndMoiveGrade(HttpServletRequest request, HttpServletResponse response){
		int movie_no= Integer.parseInt(request.getParameter("movie_no"));
		ArrayList<LocalInfoVO> local_list=null;
		int movie_grade=0;
		try {
			local_list = reserVationService.getLocalListByMovieNo(movie_no);
			movie_grade=reserVationService.getMovieGradeByMovieNo(movie_no);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}				
		
		HashMap map = new HashMap();
		map.put("movie_grade", movie_grade);
		map.put("localList",local_list);
		System.out.println(map.toString());
		return new ModelAndView("JsonView","list",map);
	}
	/*
	 * 지역정보에 따른 영화관 정보
	 */
	public ModelAndView getTheaterListByLocal(HttpServletRequest request, HttpServletResponse response){
		
		System.out.println("getTheaterListByLocal");
		int local_no= Integer.parseInt(request.getParameter("local_no"));
		int movie_no=Integer.parseInt(request.getParameter("movie_no"));
		System.out.println(local_no);
		HashMap map=new HashMap();
		map.put("local_no", local_no);
		map.put("movie_no", movie_no);
		ArrayList<HashMap> theater_list=null;
		try {
			theater_list = reserVationService.getTheaterListByLocalAndMovie(map);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("return ok");
		System.out.println(theater_list.toString());
		return new ModelAndView("JsonView","theater",theater_list);
	}
	public ModelAndView getMovieGradeByMovieNo(HttpServletRequest request, HttpServletResponse response){
		int movie_no= Integer.parseInt(request.getParameter("movie_no"));
		int movie_grade=0;
		try {
			movie_grade = reserVationService.getMovieGradeByMovieNo(movie_no);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ModelAndView("JsonView","movie_grade",movie_grade);
	}
	/**
	 * 영화, 영화관, 날짜에 해당하는 상영시간표 
	 * 	- 상영시간표는 현재 시간보다 큰 값들만 갖고 온다. 
	 */
	public ModelAndView getTimeTableList(HttpServletRequest request, HttpServletResponse response){
		System.out.println("getTimeTableList");
		int movie_no=Integer.parseInt(request.getParameter("movie_no"));
		int theater_no=Integer.parseInt(request.getParameter("theater_no"));
		
		String date=request.getParameter("date");
		System.out.println(movie_no+"/"+theater_no+"/"+date+"/");
		// 영화관 번호 vo에 입력....
		TheaterVO theaterVO= new TheaterVO(theater_no);
		PlayRoomVO prVO= new PlayRoomVO(theaterVO);		
		// 영화 번호 vo....
		MovieVO mVO= new MovieVO(movie_no);		
		TimeTableVO ttVO= new TimeTableVO(mVO, prVO, date);
		// 잔여좌석 정보
		ArrayList<HashMap> timeList=null;
		try {
			timeList = reserVationService.getTimeTableList(ttVO);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		/*
		 * 예약된 좌석수 조회 
		 */
		for(HashMap map:timeList){
			int timetable_no= Integer.parseInt(((BigDecimal)map.get("NO")).toString());
			ArrayList<String> confirmedSeat=null;
			try {
				confirmedSeat = reserVationService.getConfirmedSeat(timetable_no);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String seat="";
			ArrayList arrSeat =new ArrayList();
			for(String str:confirmedSeat){
				seat+=str+",";
			}
			StringTokenizer st= new StringTokenizer(seat,",");
			while(st.hasMoreTokens()){				
				arrSeat.add(st.nextToken());				
			}
			// 예약된 좌석 수를 map에 추가
			map.put("CONFIRMEDSEAT", arrSeat.size());		
		}		
		return new ModelAndView("JsonView","timeList",timeList);
		
	}
	
	/**
	 * 좌석 선택
	 */
	public ModelAndView seat(HttpServletRequest request, HttpServletResponse response){
		System.out.println("seat join..");
		int movie_no=Integer.parseInt(request.getParameter("movie_no"));
		int theater_no=Integer.parseInt(request.getParameter("theater_no"));
		String date=request.getParameter("date");
		int timetable_no=Integer.parseInt(request.getParameter("timetable_no"));
		System.out.println("timetable_no : "+timetable_no);
		int adult=Integer.parseInt(request.getParameter("adult"));
		int youth=0;
		if(request.getParameter("youth") != null){
			youth=Integer.parseInt(request.getParameter("youth"));
		}
		HashMap map= new HashMap();
		map.put("movie_no", movie_no);
		map.put("theater_no", movie_no);
		map.put("date", date);
		map.put("timetable_no", timetable_no);
		map.put("adult", adult);
		map.put("youth", youth);
		map.put("count", adult+youth);	
		String info = "&movie_no="+movie_no+"&theater_no="+theater_no
							+"&date="+date+"&timetable_no="+timetable_no
							+"&adult="+adult+"&youth="+youth;
		System.out.println(info);	
		request.setAttribute("info", info);		
		request.setAttribute("infoMap",map);
		
		/*
		 * 예약된 좌석 정보
		 */
		ArrayList<String> seatList=null;
		try {
			seatList = reserVationService.getConfirmedSeat(timetable_no);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String confirmedSeat="";
		for(String str:seatList){
			confirmedSeat+= str+",";
		}
	
		request.setAttribute("seatList", confirmedSeat);
		return new ModelAndView("seat.reservation");
	}
	/**
	 * 결제창 - 팝업
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException 
	 */
	public ModelAndView credit_pop(HttpServletRequest request, HttpServletResponse response){
		System.out.println("credit-pop..");
		Map map = new HashMap();
		
		// 1. movie_title, theater, play_room_no,starting_time, ending_time  
		int timetable_no=Integer.parseInt(request.getParameter("timetable_no"));		
		ArrayList<HashMap> list=null;
		try {
			list = reserVationService.getReservationConfirm(timetable_no);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("리스트 ...");
		System.out.println(list.toString());
		map.put("tt_info", list);
		map.put("timetable_no",timetable_no);
		//2. 선택한 좌석 보여준다.
		String seat=request.getParameter("seat");
		map.put("seat", seat);
		//3. 결제방식 가져온다
		ArrayList<PaymentMethodInfoVO> pMethod=null;
		try {
			pMethod = reserVationService.getPaymentMethodInfo();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		map.put("pMethod", pMethod);
		//4. 성인+청소년
		int adult=Integer.parseInt(request.getParameter("adult"));
		int youth=Integer.parseInt(request.getParameter("youth"));
		int adultCost = adult*PaymentConstants.ADULT_FEE;
		int youthCost = youth*PaymentConstants.YOUTH_FEE;
		int AllCost=adultCost+youthCost;
		// 티켓, 가격
		map.put("ticketCount", adult+youth);
		map.put("AllCost",AllCost);
		
		System.out.println("선택어른수 : "+adult+"/선택 어린이수:"+youth);
		System.out.println("어른요금 : "+adultCost+"어린이요금 : "+youthCost);
		System.out.println("아영 : "+map.toString());
		return new ModelAndView("main/reservation/credit-pop","info",map);
	}
	/**
	 * 결제 완료
	 * 결제 정보 db에 입력....
	 * @throws SQLException 
	 */
	public ModelAndView reservationOK(HttpServletRequest request, HttpServletResponse response){
		System.out.println("reservationOK");
	
		int time_table_no=Integer.parseInt(request.getParameter("timetable_no"));
		int method=Integer.parseInt(request.getParameter("pMethod"));
		System.out.println(time_table_no+" "+method);
		int price= Integer.parseInt(request.getParameter("price"));
	    int ticketCount= Integer.parseInt(request.getParameter("ticketCount"));
		// 좌석정보 - 좌석 구분자로 , 사용
		String seat_no=request.getParameter("seat");		

		// timetable_no 로 play_Room_uniq_no, movie_no, 상영시간표 알수 있음.... 
		TimeTableVO ttVO= new TimeTableVO();		
		ttVO.setTime_table_no(time_table_no);

		// 결제 방식
		PaymentMethodInfoVO pmiVO = new PaymentMethodInfoVO();
		int payment_no= Integer.parseInt(request.getParameter("pMethod"));	
		pmiVO.setPayment_no(payment_no);
		
		// 회원정보
		MemberVO mVO=(MemberVO) request.getSession().getAttribute("vo");
		System.out.println(mVO);
		/*	
		 * 1차
		 * 		결제금액은.... 어른, 청소년 기본요금으로만 계산한다.
		 * 2차
		 * 		요일정보에 따른 adult 추가 요금 발생
		 * 		시간에 따른 영화 금액 적용 - 2차
		 */
	
		// 예매정보 insert
		ReservationVO rVO= new ReservationVO(0,ttVO,pmiVO,mVO,ticketCount,seat_no,"",price);
		System.out.println("예매정보 insert");
		System.out.println(rVO.toString());
		try {
			reserVationService.setReservationInfo(rVO);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return new ModelAndView("JsonView");
	}

	/**
	 * 예매 - 예매 확인/취소
	 * @throws SQLException 
	 */
	public ModelAndView res_confirm(HttpServletRequest request, HttpServletResponse response){
		System.out.println("res_confirm join..");	
		ArrayList<Map> list = null;
		if(request.getSession().getAttribute("vo")!=null){
		MemberVO vo = (MemberVO) request.getSession().getAttribute("vo");
		list = reserVationService.getReservationList(vo.getMember_no());
		System.out.println("res list : "+list);
		}
		return new ModelAndView("res_confirm.reservation","map",list);
	}
	public ModelAndView reservationDelete(HttpServletRequest request, HttpServletResponse response){
		System.out.println("reservationDelete join.. list : "+request.getParameter("list"));
		ArrayList<String> list = getStringFormat(request.getParameter("list"));
		System.out.println("delete list : " + list);
		reserVationService.reservationDelete(list);
		return new ModelAndView("JsonView");
	}
	public ArrayList<String> getStringFormat(String str){
		ArrayList<String> list = new ArrayList();
		StringBuffer sb = new StringBuffer(str);
		while(true){
			int index = sb.indexOf(",");
			if(index==-1)
				break;
			list.add(sb.substring(0, index));
			sb.delete(0, index+1);
		}
		list.add(sb.toString());
		return list;
	}
}
